#include "bellman.h"
#include <stdlib.h>
#include <stdio.h>

extern A_exp absyn_root;
extern FILE *yyin;
extern Temp_tempList templist;

int main(int argc, char **argv)
{
    T_stmList list, ptr;
    AS_instrList instr;
    struct C_block block;
    T_stmList listNew, listOld = NULL, listResult = NULL;
    G_graph flowGraph;
    struct COL_result color;
    Temp_tempList temp_ptr;

    printf("%d %s", argc, argv[1]);
    if (argc != 2)
    {
        printf("Usage: bellman filename\n");
        exit(1);
    }

    EM_reset(argv[1]);
    if (!yyin)
    {
        fprintf(stderr, "Error while trying to open input file!\n");
        exit(1);
    }

    // call flex and bison routine to parse the source
    yyparse();
    if (!absyn_root)
    {
        fprintf(stderr, "Error while parsing the source!\n");
        exit(1);
    }

    // semantic translation
    list = SEM_transProg(absyn_root);

    // linearize the list 
    ptr = list;
    while(ptr)
    {
        listNew = C_linearize(ptr->head);
        if (!listOld)
        {
            listResult = listOld = listNew;
        }
        else
        {
            listOld->tail = listNew;
            listOld = listNew;
        }
        ptr = ptr->tail;
    }
    block = C_basicBlocks(listResult);
    listResult = C_traceSchedule(block);

    // generate the assembly
    instr = F_codegen(Tr_outermost()->frame, listResult);
    // and then the flow graph and the conflict graph
    flowGraph = FG_AssemFlowGraph(instr);

    COL_init();
    color = COL_colorVar(flowGraph);

    // print all register assignment
    temp_ptr = templist;
    while(temp_ptr)
    {
        char* regname = Temp_look(color.coloring, temp_ptr->head);
        printf ("reg: %s\n", regname);
        temp_ptr = temp_ptr->tail;
    }

    U_mainEnd();
}